package com.adjaisd.scarecrow.controller;


import com.adjaisd.scarecrow.common.result.Result;
import com.adjaisd.scarecrow.common.utils.jwt.JwtUtils;
import com.adjaisd.scarecrow.dto.QuotaAllInfo;
import com.adjaisd.scarecrow.entity.Alarm;
import com.adjaisd.scarecrow.entity.Device;
import com.adjaisd.scarecrow.entity.Quota;
import com.adjaisd.scarecrow.service.AlarmService;
import com.adjaisd.scarecrow.service.DeviceService;
import com.adjaisd.scarecrow.service.QuotaService;
import com.adjaisd.scarecrow.vo.Pager;
import com.google.common.base.Strings;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author adjaisd
 * @since 2022-03-28
 */
@RestController
@RequestMapping("/alarm")
public class AlarmController {

    @Autowired
    AlarmService alarmService;

    @ApiOperation(value = "获取报警列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public Result getAlarmList(HttpServletRequest request) {
        String token = request.getHeader("X-token");
        Claims claims = JwtUtils.getMembers(token);
        long userId = Long.parseLong(claims.get("id").toString());

        List<Alarm> alarms = alarmService.getAlarmListByUID(userId);
        return Result.succ().code(200).data("alarmList", alarms).message("查询报警成功");
    }

    @Autowired
    QuotaService quotaService;

    @ApiOperation(value = "添加报警")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public Result addAlarm(HttpServletRequest request, @RequestBody Map<String, String> alarmForm) {
        String token = request.getHeader("X-token");
        Claims claims = JwtUtils.getMembers(token);
        long userId = Long.parseLong(claims.get("id").toString());

        try {
            long quotaId = Long.parseLong((alarmForm.get("quotaId")));
            String name = alarmForm.get("name");
            String operator = alarmForm.get("operator");

            double threshold = Double.parseDouble(alarmForm.get("threshold"));
            int level = Integer.parseInt(alarmForm.get("level"));
            double cycle = Double.parseDouble(alarmForm.get("cycle"));
            String webhook = alarmForm.get("webhook");
            long time = new Date().getTime();
            Alarm alarm = new Alarm(null, name, operator, threshold, level, cycle, webhook, time, quotaId);

            System.out.println("alarm = " + alarm);
            Quota quota = quotaService.getQuotaByID(quotaId, userId);
            if (quota == null || quota.getCreateTime() == 0L)
                return Result.fail().code(400).message("不存在该指标");
            else if (!quota.getOwnerId().equals(userId))
                return Result.fail().code(400).message("不存在该指标");

            Alarm a = alarmService.getAlarm(quotaId, name, operator);

            if (a != null) {    // 报警是否存在
                if (a.getCreateTime() != 0L)
                    return Result.fail().code(400).message("已存在该报警");
                alarm.setId(a.getId());
                alarmService.updateById(alarm);
            } else {
                alarmService.addAlarm(alarm);
                Alarm t = alarmService.getAlarm(quotaId, name, operator);
                alarm.setId(t.getId());
            }
            return Result.succ().code(200).data("alarm", alarm).message("添加报警成功");
        } catch (Exception e) {
            return Result.fail().code(50015).message("缺少必要参数");
        }
    }

    @ApiOperation(value = "删除报警")
    @ApiImplicitParam(name = "alarmForm", required = true, value = "报警信息表", paramType = "body", dataType = "json")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public Result delAlarm(HttpServletRequest request, @RequestBody Map<String, String> alarmForm) {
        String token = request.getHeader("X-token");
        Claims claims = JwtUtils.getMembers(token);
        long userId = Long.parseLong(claims.get("id").toString());

        try {
            long quotaId = Long.parseLong((alarmForm.get("quotaId")));
            String name = alarmForm.get("name");
            String operator = alarmForm.get("operator");

            Alarm alarm = alarmService.getAlarm(quotaId, name, operator);
            if (alarm != null) {
                if (alarm.getCreateTime() == 0L)
                    return Result.fail().code(400).message("不存在该报警");

                if (alarmService.delAlarm(quotaId, name, operator))
                    return Result.succ().code(200).message("删除成功");
                else return Result.fail().code(400).message("删除失败");
            } else return Result.fail().code(400).message("不存在该报警");
        } catch (Exception e) {
            return Result.fail().code(50015).message("缺少必要参数");
        }
    }

    @ApiOperation(value = "更新报警")
    @ApiImplicitParam(name = "alarmForm", required = true, value = "报警信息表", paramType = "body", dataType = "json")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Result updateAlarm(HttpServletRequest request, @RequestBody Map<String, String> alarmForm) {
        String token = request.getHeader("X-token");
        Claims claims = JwtUtils.getMembers(token);
        long userId = Long.parseLong(claims.get("id").toString());
        try {
            // 不可变
            long quotaId = Long.parseLong((alarmForm.get("quotaId")));
            String name = alarmForm.get("name");
            String operator = alarmForm.get("operator");

            // 可变
            double threshold = Double.parseDouble(alarmForm.get("threshold"));
            int level = Integer.parseInt(alarmForm.get("level"));
            double cycle = Double.parseDouble(alarmForm.get("cycle"));
            String webhook = alarmForm.get("webhook");

            Alarm alarm = alarmService.getAlarm(quotaId, name, operator);
            if (alarm != null) {
                if (alarm.getCreateTime() == 0L)
                    return Result.fail().code(400).message("不存在该报警");
                alarm.setThreshold(threshold);
                alarm.setLevel(level);
                alarm.setCycle(cycle);
                alarm.setWebhook(webhook);
                if (alarmService.updateById(alarm))
                    return Result.succ().code(200).message("更新报警成功");
                else
                    return Result.fail().code(500).message("更新失败");
            } else return Result.fail().code(400).message("不存在该报警");
        } catch (Exception e) {
            return Result.fail().code(50015).message("缺少必要参数");
        }
    }

    @Autowired
    DeviceService deviceService;

    @ApiOperation(value = "查询报警日志")
    @ApiImplicitParam(name = "alarmForm", required = true, value = "报警日志信息表", paramType = "body", dataType = "json")
    @RequestMapping(value = "/log", method = RequestMethod.POST)
    @ResponseBody
    public Result getAlarmLog(HttpServletRequest request, @RequestBody Map<String, String> alarmForm) {
        String token = request.getHeader("X-token");
        Claims claims = JwtUtils.getMembers(token);
        long userId = Long.parseLong(claims.get("id").toString());
        String start, end;
        // 必要
        try {
            start = alarmForm.get("start");
            end = alarmForm.get("end");
        } catch (Exception e) {
            return Result.fail().code(400).message("缺少必要参数");
        }

        long page = 1L, pageSize = 10L;
        String alarmName = "";
        String deviceId = "";
        if (alarmForm.containsKey("page")) page = Long.parseLong(alarmForm.get("page"));
        if (alarmForm.containsKey("pageSize")) pageSize = Long.parseLong(alarmForm.get("pageSize"));
        if (alarmForm.containsKey("alarmName")) alarmName = alarmForm.get("alarmName");
        if (alarmForm.containsKey("deviceId")) {
            deviceId = alarmForm.get("deviceId");
            Device device = deviceService.getDeviceByID(Long.valueOf(deviceId));
            // 检测是否拥有者
            if (!device.getOwnerId().equals(userId))
                return Result.fail().code(400).message("没有该设备");
        }

        Pager<QuotaAllInfo> pager = alarmService.queryAlarmLogByUID(userId, page, pageSize, start, end, alarmName, deviceId);
        return Result.succ().code(200).data("pager", pager).message("查询报警分页成功");
    }

}
